<?php


namespace app\model;

use app\exception\ModelException;
use Exception;
use think\facade\Log;

class Plugin extends Model
{
    /**
     * 获取插件列表
     */
    public function getList()
    {
        $dirs = array_map('basename', glob(CMS_ROOT . 'plugins/*', GLOB_ONLYDIR));
        if ($dirs === false) {
            $this->error = lang('插件目录不可读');
            return false;
        }
        $plugins = [];

        if (empty($dirs)) return $plugins;

        $list = $this->select();
        foreach ($list as $plugin) {
            $plugins[$plugin['name']] = $plugin;
        }

        foreach ($dirs as $pluginDir) {
            $pluginDir = parse_name($pluginDir);
            if (!isset($plugins[$pluginDir])) {
                $class = get_plugin_class($pluginDir);
                if (!class_exists($class)) { // 实例化插件失败忽略
                    Log::error($class . lang('实例化插件失败'));
                    continue;
                }
                $obj                 = new $class;
                $plugins[$pluginDir] = $obj->info;

                $plugins[$pluginDir]['has_admin'] = $obj->hasAdmin;

                if (!isset($obj->info['type']) || $obj->info['type'] == 1) {//只获取普通插件
                    if ($plugins[$pluginDir]) {
                        $plugins[$pluginDir]['status'] = 3;//未安装
                    }
                } else {
                    unset($plugins[$pluginDir]);
                }

            }
        }

        $plugins = array_values($plugins);
        return $plugins;
    }

    /**
     * 修改信息
     * @param $where
     * @param $data
     * @return array
     * @throws ModelException
     */
    public function edit($where, $data)
    {
        try {
            $this->where($where)->update($data);
        } catch (Exception $e) {
            throw new ModelException($e->getMessage(), -1);
        }
        return dataReturn(0, lang('操作成功'));
    }
}
